package com.nf.health.app.activity.miansearch;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.nf.health.app.activity.miansearch.adapter.ListMainSearchAdapter;
import com.nf.health.app.customview.DragListView;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.miansearch.impl.OnChecktemLinstener;
import com.nf.health.app.customview.ShowMyTextSearchPopupWindow;
import com.nf.health.app.customview.ShowMyTextSearchPopupWindow3;
import com.nf.health.app.customview.ShowOfferMyTextSearchPopupWindow;
import com.nf.health.app.http.Act;
import com.nf.health.app.models.SearchMainDocBean;
import com.nf.health.app.service.ServiceData;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.LocationUtil;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.ViewUtil;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 新版的医生详情
 * @author yyh
 */
public class MainSearchDocActivity2  extends BaseActivity{
    private Context cnt;
    @Bind(R.id.titlebar_title_search_back)
    TextView titlebar_title_search_back;

    @Bind(R.id.ll_search_area)
    LinearLayout ll_search_area;
    @Bind(R.id.tv_search_area)
    TextView tv_search_area;
    @Bind(R.id.ll_search_ks)
    LinearLayout ll_search_ks;
    @Bind(R.id.tv_search_ks)
    TextView tv_search_ks;
    @Bind(R.id.ll_search_service)
    LinearLayout ll_search_service;
    @Bind(R.id.tv_search_service)
    TextView tv_search_service;
    @Bind(R.id.ll_content_search_view)
    LinearLayout ll_content_search_view;
    @Bind(R.id.swipe_search_refresh_layout)
    SwipeRefreshLayout swipe_search_refresh_layout;
    @Bind(R.id.el_main_search)
    EditText el_main_search;
    @Bind(R.id.tv_open_gps)
    TextView tv_open_gps;
    @Bind(R.id.rl_location_tip)
    RelativeLayout rl_location_tip;
    @Bind(R.id.ll_nodata)
    LinearLayout ll_nodata;
    @Bind(R.id.recyclerView_search)
    DragListView recyclerView_search;
    private ListMainSearchAdapter listMainSearchAdapter;
    private List<SearchMainDocBean> listSearchMainBean = new ArrayList<>();
    private ShowMyTextSearchPopupWindow showMyTextSearchPopupWindow;
    private ShowOfferMyTextSearchPopupWindow showOfferMyTextSearchPopupWindow;
    private ShowMyTextSearchPopupWindow3 showMyTextSearchPopupWindow3 = null;
    private String area = "";String department ="";String hospitalid ="";String keywords =""; int pageNo =1;String servername="";
    private int pageSize= 20;
    private boolean isPullToRefreshed = true;//是不是上拉刷新还是下拉加载
    private boolean isOpenLoadtion = false;//是不是开启定位
    private int lastVisibleItem;//最后一条索引值
    private String locationAddress;//定位到的地址
    private LinkedList<String> subLinkedList = new LinkedList<>();//医生服务选项
    private LinearLayoutManager mLayoutManager;
    private   int mListViewHeight;
    //public static boolean isShowAreaLeftImg = false;//手否显示area左侧小图标，显示当前的城市是定位的城市
    LinkedHashMap<String,LinkedList<String>> listArea = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_mainsearchdocactivity);
        ButterKnife.bind(this);
        initView();
        initEdittextListener();
        addEdittextListener();
    }

    private void initView() {
        String source = "开启定位";
        tv_search_ks.setText("全部科室");
        tv_search_service.setText("全部服务");
        tv_search_area.setText("全国");
        tv_open_gps.setText(Html.fromHtml("<u>" + "<font color='#2E86F4'>" + source + "</font>" + "</u>"));
        swipe_search_refresh_layout.setColorSchemeResources(R.color.theme_color, android.R.color.holo_red_light, android.R.color.holo_green_light, android.R.color.holo_orange_light);
        listMainSearchAdapter = new ListMainSearchAdapter(this, listSearchMainBean);
        recyclerView_search.setAdapter(listMainSearchAdapter);
        swipe_search_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isPullToRefreshed = true;
                pageNo = 1;
                loadData(pageNo);
            }
        });

        /*recyclerView_search.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                isPullToRefreshed = false;
                pageNo++;
                loadData(pageNo);
            }
        });*/
        cnt = MainSearchDocActivity2.this;
        titlebar_title_search_back.setOnClickListener(this);
        ll_search_area.setOnClickListener(this);
        ll_search_ks.setOnClickListener(this);
        tv_open_gps.setOnClickListener(this);
        ll_search_service.setOnClickListener(this);
        tv_search_area.setOnClickListener(this);
        tv_search_ks.setOnClickListener(this);
        tv_search_service.setOnClickListener(this);
        loadData(1);
        getDoctorServiceList();
        listArea = ServiceData.getMyCityArea2(cnt);
        recyclerView_search.setRefreshableAndLoadMoreable(false, true);

        recyclerView_search.setOnRefreshAndLoadMoreListener(new DragListView.onRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {

            }
            @Override
            public void onLoadMore() {
                isPullToRefreshed = false;
                pageNo++;
                loadData(pageNo);
            }
        });
    }

    /**
     * 获取搜索到的数据
     */
    private void loadData(int pageNo){
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
    /**
     *根据条件进行查询 : 区域
     */
    private void questionDataBySome(String keywords){
        this.keywords = keywords;
        pageNo = 1;
        isPullToRefreshed = true;
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
    /**
     *根据条件进行查询 : 区域
     */
    private void questionDataByAres(String area){
        this.area = area;
        pageNo = 1;
        isPullToRefreshed = true;
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
    /**
     *根据条件进行查询 : 科室
     */
    private void questionDatabyDepartment(String department){
        this.department = department;
        pageNo = 1;
        isPullToRefreshed = true;
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
    /**
     *根据条件进行查询 : 服务
     */
    private void questionDataByService(String servername){
        this.servername = servername;
        pageNo = 1;
        isPullToRefreshed = true;
        provider.queryDoctorBySomeWay(area, department, hospitalid, keywords, String.valueOf(pageNo), String.valueOf(pageSize), servername);
    }
    /**
     * 获取医生服务下拉框
     */
    private void getDoctorServiceList(){
        provider.getDoctorServiceList();
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        switch (actionName){
            case Act.Flag.SEARCH_DOCTOR_KESHI_HOSTIPAL_FLG:
                if(swipe_search_refresh_layout == null){
                    swipe_search_refresh_layout = (SwipeRefreshLayout) findViewById(R.id.swipe_search_refresh_layout);
                }
                swipe_search_refresh_layout.setRefreshing(false);
                break;
            case Act.Flag.GET_DOCTORSERVICE_LIST_FLG:
                break;
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        switch (actionName){
            case Act.Flag.SEARCH_DOCTOR_KESHI_HOSTIPAL_FLG:
                List<SearchMainDocBean> subListSearchMainBean =( List<SearchMainDocBean>) object;
                recyclerView_search.completeLoadMore();
                if(isPullToRefreshed){
                    listSearchMainBean.clear();
                    listSearchMainBean.addAll(subListSearchMainBean);
                    if(subListSearchMainBean.size() < pageSize){
                        recyclerView_search.setRefreshableAndLoadMoreable(false,false);
                    }else{
                        recyclerView_search.setRefreshableAndLoadMoreable(false,true);
                    }
                }else{
                    listSearchMainBean.addAll(subListSearchMainBean);
                    if(subListSearchMainBean.size() < pageSize){
                        recyclerView_search.setRefreshableAndLoadMoreable(false,false);
                    }else{
                        recyclerView_search.setRefreshableAndLoadMoreable(false,true);
                    }
                }
                listMainSearchAdapter.setDoctorCommentData(listSearchMainBean);
                swipe_search_refresh_layout.setRefreshing(false);
                setMyVisibile();
                break;
            case Act.Flag.GET_DOCTORSERVICE_LIST_FLG:
                subLinkedList.clear();
                subLinkedList.add("全部服务");
                JSONArray array = null;
                try {
                    array = new JSONArray(object.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                    return ;
                }
                if(array.length() > 0){
                    for (int i = 0; i < array.length(); i++) {
                        String ss = array.optString(i);
                        subLinkedList.add(ss);
                    }
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.titlebar_title_search_back:
                finish();
                break;
            case R.id.tv_open_gps://开启定位
                LocationUtil.setGoGPSMain(MainSearchDocActivity2.this);
                break;
            case R.id.ll_search_area://选择区域
            case R.id.tv_search_area:
                if(showMyTextSearchPopupWindow == null){
                    showMyTextSearchPopupWindow = new ShowMyTextSearchPopupWindow(MainSearchDocActivity2.this)
                            .initMyTextViewStatus(tv_search_area, tv_search_ks, tv_search_service, isOpenLoadtion)
                            .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                                @Override
                                public void onClickFirstMenu(String mainResult) {
                                    if (mainResult.contains("全国")) {
                                        tv_search_area.setText("" + mainResult);
                                        if(!TextUtils.isEmpty(getLocationAddress())){
                                            if(mainResult.contains(getLocationAddress())){
                                                ViewUtil.setTextImgBackground3(tv_search_area, cnt,0,R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
                                            }else{
                                                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,  0, R.drawable.inquiey_detail_arrowdown, 0);
                                            }
                                        }
                                        mainResult = "";
                                    } else {
                                        tv_search_area.setText("" + mainResult);
                                    }
                                    questionDataByAres(mainResult);
                                }

                                @Override
                                public void onClickSecondMenu(String subResult) {
                                    if (subResult.contains("|")) {
                                        String subResultArray[] = subResult.split("\\|");
                                        if (subResult.contains("全部")) {
                                            subResult =  subResultArray[0];
                                            tv_search_area.setText("" + subResultArray[0]);
                                        }else{
                                            subResult =  subResultArray[1];
                                            tv_search_area.setText("" + subResultArray[1]);

                                        }
                                        if(!TextUtils.isEmpty(getLocationAddress())){
                                            if(getLocationAddress().contains(subResultArray[0])){
                                                ViewUtil.setTextImgBackground3(tv_search_area, cnt,0,R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
                                            }else{
                                                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0,0,  0, R.drawable.inquiey_detail_arrowdown, 0);
                                            }
                                        }
                                    }
                                    questionDataByAres(subResult);
                                }
                            });
                    showMyTextSearchPopupWindow.setMyListData2(listArea, getLocationAddress(), isOpenLoadtion);
                }else{
                    showMyTextSearchPopupWindow.refreshMylocationData(getLocationAddress(),isOpenLoadtion);
                }
                if(!showMyTextSearchPopupWindow.isShowing()){
                    tv_search_area.setTextColor(getResources().getColor(R.color.theme_color));
                    tv_search_ks.setTextColor(getResources().getColor(R.color.gray));
                    tv_search_service.setTextColor(getResources().getColor(R.color.gray));
                    showMyTextSearchPopupWindow.showAsDropDown(ll_content_search_view);
                    Drawable[] ss = tv_search_area.getCompoundDrawables();
                    if(ss[0] != null){
                        ViewUtil.setTextImgBackground3(tv_search_area, cnt,0,R.drawable.iv_location, 0, R.drawable.iv_blue_arrowup, 0);
                    }else{
                        ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, 0, 0, R.drawable.iv_blue_arrowup, 0);
                    }
                }
                break;
            case R.id.tv_search_ks://选择科室
            case R.id.ll_search_ks:
                if(showOfferMyTextSearchPopupWindow == null){
                    showOfferMyTextSearchPopupWindow = new ShowOfferMyTextSearchPopupWindow(MainSearchDocActivity2.this)
                            .initMyTextViewStatus(tv_search_ks, tv_search_ks, tv_search_service, isOpenLoadtion)
                            .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                                @Override
                                public void onClickFirstMenu(String mainResult) {
                                    if(mainResult.contains("全部")){
                                        tv_search_ks.setText(mainResult);
                                        mainResult = "";
                                    }else{
                                        tv_search_ks.setText(mainResult);
                                    }
                                    questionDatabyDepartment(mainResult);
                                }
                                @Override
                                public void onClickSecondMenu(String subResult) {
                                    if(subResult.contains("全部")){
                                        tv_search_ks.setText(subResult);
                                        subResult = "";
                                    }else{
                                        if(subResult.contains("|")){
                                            String subResultArray [] =    subResult.split("\\|");
                                            tv_search_ks.setText(""+subResultArray[1]);
                                        }
                                    }
                                    questionDatabyDepartment(subResult);
                                }
                            });
                    showOfferMyTextSearchPopupWindow.setMyListData2(ServiceData.getMyOfferData(cnt));
                }else {
                    showOfferMyTextSearchPopupWindow.showMyMuneRefresh();
                }
                if(!showOfferMyTextSearchPopupWindow.isShowing()){
                    tv_search_area.setTextColor(this.getResources().getColor(R.color.gray));
                    tv_search_ks.setTextColor(getResources().getColor(R.color.theme_color));
                    tv_search_service.setTextColor(getResources().getColor(R.color.gray));
                    showOfferMyTextSearchPopupWindow.showAsDropDown(ll_content_search_view);
                    ViewUtil.setTextImgBackground2(tv_search_ks, cnt, ViewUtil.TextMode.RIGHT, 0, R.drawable.iv_blue_arrowup);
                }
                break;
            case R.id.tv_search_service://选择服务
            case R.id.ll_search_service:
                if(showMyTextSearchPopupWindow3 == null){
                    showMyTextSearchPopupWindow3 = new ShowMyTextSearchPopupWindow3(MainSearchDocActivity2.this)
                            .initMyTextViewStatus(tv_search_area, tv_search_ks, tv_search_service)
                            .regisitMyMenuOnClickListaner(new OnChecktemLinstener() {
                                @Override
                                public void onClickFirstMenu(String mainResult) { }
                                @Override
                                public void onClickSecondMenu(String subResult) {
                                    tv_search_service.setText(subResult);
                                    if(subResult.contains("全部")){
                                        subResult = "";
                                    }
                                    questionDataByService(subResult);
                                }
                            });
                    showMyTextSearchPopupWindow3.setMyListData(subLinkedList);
                }else{
                    showMyTextSearchPopupWindow3.refreshMylocationData(subLinkedList,isOpenLoadtion);
                }
                if(!showMyTextSearchPopupWindow3.isShowing()){
                    tv_search_area.setTextColor(getResources().getColor(R.color.gray));
                    tv_search_ks.setTextColor(getResources().getColor(R.color.gray));
                    tv_search_service.setTextColor(getResources().getColor(R.color.theme_color));
                    showMyTextSearchPopupWindow3.showAsDropDown(ll_content_search_view);
                    ViewUtil.setTextImgBackground2(tv_search_service, cnt, ViewUtil.TextMode.RIGHT, 0, R.drawable.iv_blue_arrowup);
                }
                break;

        }
        super.onClick(v);
    }
    private void initEdittextListener() {
        el_main_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    String someQuestion = el_main_search.getText().toString();
                    if (TextUtils.isEmpty(someQuestion)) {
                        GetToast.useString(cnt, "条件不能为空");
                        return false;
                    }
                    questionDataBySome(someQuestion);
                    return true;
                }
                return false;

            }

        });
    }

    /**
     * 定位相关
     */
    public void initMyLocation(){
        LocationUtil.initial(cnt, new LocationUtil.CallAddressBack() {
            @Override
            public void complete(double latitude, double longitude, String address) {
                LogUtil.e("yuyahao", "经：" + latitude + " wei: " + " longitude " + longitude + " 地址： " + address);
                // TODO Auto-generated method stub
                String longitudeStr = String.valueOf(longitude);
                String latitudeStr = String.valueOf(latitude);
                isOpenLoadtion = true;
                String getMyLocationAddress = ServiceData.getCityDefaultPosition2(listArea, address);

                try {
                    if (!TextUtils.isEmpty(getMyLocationAddress)) {
                        String cityArray[] = getMyLocationAddress.split("\\|");
                        tv_search_area.setText(cityArray[1]);
                        if (showMyTextSearchPopupWindow == null || !showMyTextSearchPopupWindow.isShowing()) {
                            ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
                        } else {
                            ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
                        }
                        address = getMyLocationAddress;
                    } else {
                        tv_search_area.setText("全国");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                setLocationAddress(address);
                setMyLocationShowSelectBarStatus();
                LogUtil.e("yuyahao", "经：" + longitudeStr + " wei: " + " longitude " + latitudeStr + " 地址： " + address);
            }

            @Override
            public void callRemainQuestFaild() {
                isOpenLoadtion = false;
                setMyLocationShowSelectBarStatus();
                LogUtil.e("yuyahao", "地址获取失败");
            }
        });
    }

    /**
     * 设置定位或者不定位时，选择状态栏的显示情况
     *  由于Android这边可进行网络，GPS 均可定位，
     */
    private void setMyLocationShowSelectBarStatus(){
        if(showMyTextSearchPopupWindow != null && showMyTextSearchPopupWindow.isShowing()){
            if(!isOpenLoadtion){
                rl_location_tip.setVisibility(View.VISIBLE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt,0, 0, 0, R.drawable.iv_blue_arrowup, 0);//iv_blue_arrowup  inquiey_detail_arrowdown
            }else{
                rl_location_tip.setVisibility(View.GONE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, R.drawable.iv_location, 0, R.drawable.iv_blue_arrowup, 0);
            }
        }else{
            if(!isOpenLoadtion){
                rl_location_tip.setVisibility(View.VISIBLE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt,0, 0, 0, R.drawable.inquiey_detail_arrowdown, 0);
            }else{
                rl_location_tip.setVisibility(View.GONE);
                ViewUtil.setTextImgBackground3(tv_search_area, cnt, 0, R.drawable.iv_location, 0, R.drawable.inquiey_detail_arrowdown, 0);
            }
        }
    }
    @Override
    protected void onPostResume() {
        super.onPostResume();
        initMyLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    public void setLocationAddress(String locationAddress) {
        this.locationAddress = locationAddress;
    }
    public void setMyVisibile() {//List<SearchMainDocBean> listSearchMainBean
        if(listSearchMainBean.size() == 0){
            ll_nodata.setVisibility(View.VISIBLE);
            swipe_search_refresh_layout.setVisibility(View.GONE);
        }else{
            ll_nodata.setVisibility(View.GONE);
            swipe_search_refresh_layout.setVisibility(View.VISIBLE);
        }
    }
    public String getLocationAddress() {
        return locationAddress;
    }
    public void addEdittextListener(){
        el_main_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count,int after) {
            }

            @Override
            public void afterTextChanged(Editable edit) {
                //edit  输入结束呈现在输入框中的信息
                if(!TextUtils.isEmpty(edit.toString())){
                    keywords = edit.toString();
                    questionDataBySome(keywords);
                }else{
                    questionDataBySome("");
                }
            }
        });
    }
}
